package com.jboost.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.CacheConstant;
import com.jboost.common.constant.CommonConstant;
import com.jboost.common.constant.enums.ResultCode;
import com.jboost.common.system.api.ISysBaseAPI;
import com.jboost.common.util.PasswordUtil;
import com.jboost.common.util.oConvertUtils;
import com.jboost.config.mybatis.DomainContext;
import com.jboost.modules.base.service.BaseCommonService;
import com.jboost.modules.system.entity.SysAccount;
import com.jboost.modules.system.entity.SysUser;
import com.jboost.modules.system.mapper.*;
import com.jboost.modules.system.service.ISysAccountService;
import com.jboost.modules.system.vo.SysUserAccountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: scott
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class SysAccountServiceImpl extends ServiceImpl<SysAccountMapper, SysAccount> implements ISysAccountService {

	@Autowired
	private SysAccountMapper accountMapper;
	@Autowired
	private SysPermissionMapper sysPermissionMapper;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private SysDepartMapper sysDepartMapper;
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysDepartRoleUserMapper departRoleUserMapper;
	@Autowired
	private SysDepartRoleMapper sysDepartRoleMapper;
	@Resource
	private BaseCommonService baseCommonService;

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        SysAccount user = accountMapper.getAccountByNameAndDomain(username,null,DomainContext.getDomain());
        String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
        if (!user.getPassword().equals(passwordEncode)) {
            return Result.error("旧密码输入错误!");
        }
        if (oConvertUtils.isEmpty(newpassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newpassword.equals(confirmpassword)) {
            return Result.error("两次输入密码不一致!");
        }
        String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
        this.accountMapper.update(new SysAccount().setPassword(password), new LambdaQueryWrapper<SysAccount>().eq(SysAccount::getId, user.getId()));
        return Result.ok("密码重置成功!");
    }

	@Override
	public int resetPassword(String username, String newpassword) {
		SysAccount user = accountMapper.getAccountByNameAndDomain(username,null, DomainContext.getDomain());
		String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
		return this.accountMapper.update(new SysAccount().setPassword(password), new LambdaQueryWrapper<SysAccount>().eq(SysAccount::getId, user.getId()));
	}

	@Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> changePassword(SysAccount sysAccount) {
        String salt = oConvertUtils.randomGen(8);
        sysAccount.setSalt(salt);
        String password = sysAccount.getPassword();
        String passwordEncode = PasswordUtil.encrypt(sysAccount.getAccountName(), password, salt);
        sysAccount.setPassword(passwordEncode);
        this.accountMapper.updateById(sysAccount);
        return Result.ok("密码修改成功!");
    }

	@Override
	public boolean deleteAccount(String accountId) {
		return false;
	}

	@Override
	public boolean deleteBatchAccounts(String accountIds) {
		return false;
	}

	@Override
	public SysAccount getAccountByNameAndDomain(String accountName,String phone) {
		return accountMapper.getAccountByNameAndDomain(accountName,phone,DomainContext.getDomain());
	}

	@Override
	public void addUserWithRole(SysAccount account, String roles) {

	}

	@Override
	public void editUserWithRole(SysAccount account, String roles) {

	}

	@Override
	public List<String> getRole(String accountname) {
		return null;
	}

	@Override
	public IPage<SysAccount> getUserByDepId(Page<SysAccount> page, String departId, String accountname) {
		return null;
	}

	@Override
	public IPage<SysAccount> getUserByDepIds(Page<SysAccount> page, List<String> departIds, String accountname) {
		return null;
	}

	@Override
	public Map<String, String> getDepNamesByUserIds(List<String> accountIds) {
		return null;
	}

	@Override
	public Map<String, String> getRoleNamesByUserIds(List<String> accountIds) {
		return null;
	}

	@Override
	public IPage<SysAccount> getUserByDepartIdAndQueryWrapper(Page<SysAccount> page, String departId, QueryWrapper<SysAccount> queryWrapper) {
		return null;
	}

	@Override
	public IPage<SysAccount> getUserByRoleId(Page<SysAccount> page, String roleId, String accountname) {
		return null;
	}

	@Override
	public Set<String> getUserRolesSet(String accountname) {
		return null;
	}

	@Override
	public Set<String> getUserPermissionsSet(String accountname) {
		return null;
	}

	@Override
	public void updateUserDepart(String accountname, String orgCode) {

	}

	@Override
	public SysAccount getAccountByPhone(String phone) {
		return accountMapper.getAccountByPhone(phone);
	}

	@Override
	public SysAccount getUserByEmail(String email) {
		return null;
	}

	@Override
	public void addUserWithDepart(SysAccount account, String selectedParts) {

	}

	@Override
	public void editUserWithDepart(SysAccount account, String departs) {

	}

	/**
	 * 校验用户是否有效
	 * @param sysAccount
	 * @return
	 */
	@Override
	public Result<?> checkAccountIsEffective(SysAccount sysAccount) {
		Result<?> result = new Result<Object>();
		//情况1：根据账号信息查询，该账号不存在
		if (sysAccount == null) {
			result.error500("该账号不存在，请注册");
			baseCommonService.addLog("账号登录失败，账号不存在！", CommonConstant.LOG_TYPE_1, null);
			return result;
		}
		//情况2：根据账号信息查询，该账号已注销
		//update-begin---author:王帅   Date:20200601  for：if条件永远为falsebug------------
		if (CommonConstant.DEL_FLAG_1.equals(sysAccount.getDelFlag())) {
			//update-end---author:王帅   Date:20200601  for：if条件永远为falsebug------------
			baseCommonService.addLog("账号登录失败，账号名:" + sysAccount.getAccountName() + "已注销！", CommonConstant.LOG_TYPE_1, null);
			result.error500("该账号已注销");
			return result;
		}
		//情况3：根据账号信息查询，该账号已冻结
		if (CommonConstant.USER_FREEZE.equals(sysAccount.getStatus())) {
			baseCommonService.addLog("账号登录失败，账号名:" + sysAccount.getAccountName() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
			result.error(ResultCode.FORBIDDEN.getCode(),"您的账户已停用，请联系材神云业务人员进行处理！");
			return result;
		}
		return result;
	}

	@Override
	public List<SysAccount> queryLogicDeleted() {
		return null;
	}

	@Override
	public List<SysAccount> queryLogicDeleted(LambdaQueryWrapper<SysAccount> wrapper) {
		return null;
	}

	@Override
	public boolean revertLogicDeleted(List<String> accountIds, SysAccount updateEntity) {
		return false;
	}

	@Override
	public boolean removeLogicDeleted(List<String> accountIds) {
		return false;
	}

	@Override
	public boolean updateNullPhoneEmail() {
		return false;
	}

	@Override
	public void saveThirdUser(SysAccount sysAccount) {

	}

	@Override
	public List<SysAccount> queryByDepIds(List<String> departIds, String accountname) {
		return null;
	}

	@Override
	public List<SysUser> getUserByAccountIdAndDomain(String accountId, String domain) {
		return baseMapper.getUserByAccountIdAndDomain(accountId, domain);
	}

	@Override
	public List<SysUserAccountVo> getAllUserByAccountId(String accountId) {
		return baseMapper.getAllUserByAccountId(accountId);
	}

	@Override
	public List<String> getDomainRoleNamesByAccountId(String accountId, String domain) {
		return baseMapper.getDomainRoleNamesByAccountId(accountId, domain);
	}
	@Override
	public IPage<SysAccount> pageAll(Page<SysUser> page, String key, String domain) {
		return accountMapper.pageAll(page,key,domain);
	}

	@Override
	public SysAccount getAccountByUserId(String id) {
		return baseMapper.getAccountByUserId(id);
	}

}
